package com.pet.framework.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;



public class StringUtil {
	public final static String NEWLINE = "\r";
	public final static String BLANK_SPACE = " ";
	private static final String BLANK = "";
	private static final String APP_FOLDER = "/userfiles/app";
	private static final String IMAGES_FOLDER = "/userfiles/images";
	private static final String TEMP = "temp";
	public final static String IP1 = "x-forwarded-for";
	public final static String IP2 = "Proxy-Client-IP";
	public final static String IP3 = "WL-Proxy-Client-IP";
	public final static String UNKNOWN = "unknown";
	public final static String COMMA = ",";
	private static Long IMGSEQ = 0l;
	public static boolean isEmpty(String s){
		return s == null || BLANK.compareTo(s) == 0;
    }
	public static boolean isEmpty(Object str) {
		return str == null || BLANK.equals(str);
	}
	public static int getInt(String str, int defaultVal){
		if(str!=null){
			return Integer.valueOf(str);
		}
		return defaultVal;
	}
	public static String dealNull(String str) {
		return str != null ? str.trim() : BLANK;
	}
	public static String dealNull(Object obj) {
		String str = BLANK;
		if(obj!=null){
			if(obj instanceof String){
				str = (String)obj;
			}else{
				str = obj.toString();
			}
		}
		return str;
	}
	public static String convertHtml(String str) {
		str = (str == null) ? BLANK : str;
		str = str.replaceAll(NEWLINE, "<br/>");
		str = str.replaceAll(BLANK_SPACE, "&nbsp;");
		return str;
	}
	
	public static String dealNull(Object str,String defaultValue){
		return str != null ? str.toString().trim() : defaultValue;
	}
	
	public static String dealNull(String str, String defaultVal) {
		return str != null ? str.trim() : defaultVal;
	}
	public static String encode(String str, final String encoding) {
		try {
			if (!StringUtil.isEmpty(str)) {
				str = URLEncoder.encode(str, encoding);
			}
		} catch (Exception e) {
		}
		return str;
	}
	public static boolean equals(Object value1, Object value2) {
		boolean is = false;
		if (value1 == value2) { // is null or self
			return is = true;
		}
		if (value1 != null && value2 != null) { // is not null;
			return value1.equals(value2);
		}
		return is;
	}
	public static boolean regex(String regex, String str) {
		boolean trueOrFalse;
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(str);
		trueOrFalse = m.matches();
		return trueOrFalse;
	}
	public static Integer getFileSpace(File file){
		return file==null?0:NumberUtil.getInt(file.length()/1024, 0);
	}
	//获取后缀名
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int i = filename.lastIndexOf('.');
			if ((i > -1) && (i < (filename.length() - 1))) {
				return filename.substring(i + 1);
			}
		}
		return null;
	}
	//获取文件名
	public static String getFileName(String filename){
		if ((filename != null) && (filename.length() > 0)) {
			int i = filename.lastIndexOf('/');
			if ((i > -1) && (i < (filename.length() - 1))) {
				return filename.substring(i + 1);
			}
		}
		return filename;
	}
	//获取文件名
	public static String getFileNameNoSuffix(String filename){
		if ((filename != null) && (filename.length() > 0)) {
			int i = filename.lastIndexOf('/');
			if ((i > -1) && (i < (filename.length() - 1))) {
				return filename.substring(i + 1);
			}
		}
		return filename.replaceAll("\\..*", "");
	}

	
	public static boolean createFolder(String file) {
		File folder = new File(file);
		if(!folder.exists()){
			return folder.mkdirs();
		};return true;
	}

	//上传文件
	private static void upload(File upload, String absolutePath) throws Exception {
		FileOutputStream fos = new FileOutputStream(absolutePath);
		FileInputStream fis = new FileInputStream(upload);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0) {
			fos.write(buffer, 0, len);
		}
		fis.close();
		fos.close();
	}
	public static String trim(String str){
		return StringUtil.dealNull(str).trim();
	}
	public static String subString(String str,int i){
		if(StringUtil.isEmpty(str)) return null;
		return str.length()>i?str.substring(0,i)+"...":str;
	}
	public static int random(int n){
		if(n==0) return 0;
		Random random = new Random();
		return Math.abs(random.nextInt())%n;
	}
	public static double round(double number, int bit){
		double n = Math.pow(10, bit);
		int b = (int)Math.round(number * n); //小数点后n位前移，并四舍五入 
		return (double)b / n; //还原小数点后n位
	}
	public static void mkDir(String str){
		File file = new File(str);
		if(!file.exists()){
			file.mkdir();
		}
	}

	public static String currentFileName(String fileName,Long id){
	    String ext = StringUtil.getExtensionName(fileName);
	    IMGSEQ++;
	    if(IMGSEQ>100) IMGSEQ=0l;
		return id+"_"+IMGSEQ+Long.toString(System.currentTimeMillis())+"."+ext;
	}
	//id 为 user id
	public static String currentAppFolder(Long id){
		return APP_FOLDER+"/"+id+"/";
	}
	public static String currentPackAPpFolder(Long userId,Long softId){
		return APP_FOLDER+"/"+userId+"/"+softId+"/";
	}
	public static String currentImageFolder(Long id){
		return IMAGES_FOLDER+"/"+id+"/";
	}
	
	public static String currentTempFolder(Long id){
		return APP_FOLDER+"/"+id+"/"+TEMP+"/";
	}
    public static String getProperties(String name){
    	PropertiesUtil util = PropertiesUtil.createPropertiesUtil("config/constants.properties");
        util.loadProperties();
        return  util.getProperty(name);
    }
    public static String filterIp(String ip){
    	if(StringUtil.isEmpty(ip)) return "";
    	String[][] object={new String[]{"\\.\\d*\\.",".*."},new String[]{"\\.\\d*\\.",".*."}}; 
    	return replace(ip,object);
    }
	public static String replace(final String sourceString,Object[] object) { 
        String temp=sourceString;    
        for(int i=0;i<object.length;i++){ 
           String[] result=(String[])object[i]; 
           Pattern    pattern = Pattern.compile(result[0]); 
           Matcher matcher = pattern.matcher(temp); 
           temp=matcher.replaceAll(result[1]); 
        } 
        return temp; 
    } 
	/**<b>功能说明：判断图片尺寸</b>
	 * 日期：Aug 5, 2010
	 * @author luo
	 * @param file
	 * @param width
	 * @param height
	 * @return
	 */
	public static boolean checkImgSize(File file, int width, int height) {
		try {
			BufferedImage img = ImageIO.read(file);
			if ((img.getWidth() >= width - 5 && img.getWidth() <= width + 5) && (img.getHeight() >= height - 5 && img.getHeight() <= height + 5)) {
				return true;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	public static String fillZero(String code,Integer len){
    	String s = StringUtil.dealNull(code);//code.toString();
        while(s.length()<len){
        	s="0"+s;
        }
        return s;
    }
	public static InputStream getFullPathInputStream(String path){
		try {
			URL url = new URL(path);
			HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
			return urlc.getInputStream();
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return null;
	}
	
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader(IP1);
		if (ip == null || ip.length() == 0|| UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader(IP2);
		}
		if (ip == null || ip.length() == 0|| UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader(IP3);
		}
		if (ip == null || ip.length() == 0|| UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.contains(COMMA)) {
			int i = ip.indexOf(COMMA);
			ip = ip.substring(0, i);
		}
		return ip;
	}
	public static String createUuid(){
		 return UUID.randomUUID().toString().replaceAll("-", "");
	}
	public static String formatOrderId(Date date,Integer orderId){
	        String prefix = DateUtil.getFormatDate(date, "yyyyMM");// createdTime.substring(0, tIndex).replace("-", "").substring(0, 6);        
	        return String.format("%s%06d", prefix, orderId);
	}
	public static void main(String[] args){
	
		System.out.println(new MD5Util().getMD5ofStr("hua1000"));
		System.out.println(StringUtil.createUuid());
		//String ug = "Mozilla/5.0 (Linux; Android 4.4.3; HTC 802t 16GB Build/KTU84L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 MicroMessenger/5.3.1.51_r733746.462 NetType/WIFI";   
		//System.out.println(StringUtil.formatOrderId(new Date(), 1121));

		//System.out.println(createUuid());
	    //System.out.println("ituns://app.a.com".matches("^ituns.*"));
	 
	}
}
